package com.bjbn.service.impl;

import com.bjbn.service.XmlParseService;
import com.bjbn.dto.FlightMessage;
import com.bjbn.entity.FimsDataOri;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;

/**
 * XML解析服务实现类
 * 
 * @author bjbn
 */
@Slf4j
@Service
public class XmlParseServiceImpl implements XmlParseService {

    @Override
    public FlightMessage parseXmlMessage(String xmlContent) {
        try {
            JAXBContext context = JAXBContext.newInstance(FlightMessage.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader reader = new StringReader(xmlContent);
            FlightMessage flightMessage = (FlightMessage) unmarshaller.unmarshal(reader);
            log.debug("XML解析成功，FLID: {}",
                    flightMessage.getFlightData() != null ? flightMessage.getFlightData().getFlid() : "unknown");
            return flightMessage;
        } catch (JAXBException e) {
            log.error("XML解析失败", e);
            return null;
        }
    }

    @Override
    public FimsDataOri convertToFimsData(String xmlContent, String source) {
        try {
            FlightMessage flightMessage = parseXmlMessage(xmlContent);
            if (flightMessage == null || flightMessage.getMeta() == null) {
                log.warn("XML消息解析失败或元数据为空");
                return null;
            }

            FimsDataOri fimsDataOri = new FimsDataOri();
            
            // 设置航班号
            if (flightMessage.getFlightData() != null) {
                fimsDataOri.setFlid(flightMessage.getFlightData().getFlid());
            }
            
            // 设置原始XML数据
            fimsDataOri.setData(xmlContent);
            
            // 设置元数据
            FlightMessage.Meta meta = flightMessage.getMeta();
            fimsDataOri.setSndr(meta.getSndr());
            fimsDataOri.setRcvr(meta.getRcvr());
            fimsDataOri.setSeqn(meta.getSeqn());
            fimsDataOri.setDdtm(meta.getDdtm());
            fimsDataOri.setType(meta.getType());
            fimsDataOri.setStyp(meta.getStyp());

            log.debug("转换FIMS数据成功，FLID: {}, 来源: {}", fimsDataOri.getFlid(), source);
            return fimsDataOri;
        } catch (Exception e) {
            log.error("转换FIMS数据失败", e);
            return null;
        }
    }
} 